<?php

class wms_ctl_admin_logiback_consign extends desktop_controller{

    var $workground = "wms_delivery";

    var $dlyCorp_tab = 'show';



    public function getShopIds(){
        $shop = app::get('ome')->model('shop');
        $shops = $shop->getList('shop_id', array('active' => 'true','is_sendshop'=>'false'));
        if(empty($shops) || !isset($shops)){
            return array();
        }
        $shop_ids = array();
        foreach($shops as $val){
            if(kernel::single('desktop_user')->is_super()){
                $shop_ids[] = $val['shop_id'];
                continue;
            }
            if(in_array($val['shop_id'],$this->shopIds)){
                $shop_ids[] = $val['shop_id'];
            }

        }
        return $shop_ids;
    }

    /**
     * 添加发货/单据打印下的顶部view
     */
    function _views()
    {
        if ($this->dlyCorp_tab == 'hidden') {
            return '';
        }

        $status = kernel::single('base_component_request')->get_get('status');
        $sku = kernel::single('base_component_request')->get_get('sku');

        $query = array(
            'app' => 'wms',
            'ctl' => 'admin_logiback_consign',
            'act' => 'index',
            'status' => $status,
            'sku' => $sku,
        );

        //所有自建仓
        $ownerBranch = array();
        $ownerBranch = kernel::single('ome_branch_type')->getOwnBranchIds();

        $sub_menu = $this->getView($status);
        $i = 0;
        $mdl_order = app::get('wms')->model('delivery');
        foreach ($sub_menu as $k => $v) {
            //非管理员取管辖仓与自建仓的交集
            $v['filter']['ext_branch_id'] = $v['filter']['ext_branch_id'] ? array_intersect($v['filter']['ext_branch_id'], $ownerBranch) : $ownerBranch;
            $sub_menu[$k]['filter'] = $v['filter'] ? $v['filter'] : null;
            $sub_menu[$k]['addon'] = true;
            $query['view'] = $i++;
            $query['logi_id'] = urlencode($v['filter']['logi_id']);
            $sub_menu[$k]['href'] = 'index.php?' . http_build_query($query);
            unset($v);
        }
        return $sub_menu;
    }

    function getView($status)
    {
        $oDlycorp = app::get('ome')->model('dly_corp');
        $submenu = $oDlycorp->getList('corp_id,name', array('disabled' => 'false'));
        foreach($submenu as $key=>$value){
                if($value['name']=="门店自提"||$value['name']=="门店配送"){
                        continue;
                }else{
                        $logi_filter[]=$value['corp_id'];
                }
        }
        if (empty($submenu))
            return $submenu;

        $tmp_filter = array('type' => 'normal');
        $tmp_filter['shop_id'] = $this->getShopIds();
        $tmp_filter['status'] = 3;
        $tmp_filter['is_sync_shop']='false';
        $tmp_filter['logi_id']=$logi_filter;
        $s_filter = $this->analyseStatus('');
        $tmp_filter = array_merge($tmp_filter, $s_filter);

        $oBranch = app::get('ome')->model('branch');
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super) {
            $branch_ids = $oBranch->getBranchByUser(true);
            if ($branch_ids) {
                $tmp_filter['ext_branch_id'] = $_POST['branch_id'] ? $_POST['branch_id'] : $branch_ids;
            } else {
                $tmp_filter['ext_branch_id'] = 'false';
            }
        }

        $c = 1;
        $sub_menu[0] = array(
            'label' => $tmp_filter['_title_'],
            'filter' => $tmp_filter,
            'optional' => false
        );

        #第三方发货时，显示已发货、未发货
        if ($_GET['ctl'] == 'admin_receipts_outer') {
            $c = 3;#物流公司view在未发货之后
            $outer_filter = $tmp_filter;
            #让已发货、未发货显示在全部之后
            $outer = $this->shipStatus();
            foreach ($outer as $key => $v) {
                if ($key == 'succ') {
                    $outer_filter['status'] = array(3);
                } else {
                    #所有不属于发货成功的，都是未发货
                    $outer_filter['status'] = array(0);
                    //unset($tmp_filter['status']);
                }
                $sub_menu[] = array(
                    'label' => app::get('base')->_($v),
                    'filter' => $outer_filter,
                    'optional' => false
                );
            }
        }

        foreach ($submenu as $keys => $values) {
            if($values['name']=="门店自提" || $values['name']=="门店配送"){
                continue;
            }
            $sub_menu[$c] = array(
                'label' => $values['name'],
                'filter' => array_merge($tmp_filter, array('logi_id' => $values['corp_id'])),
                'optional' => false
            );
            $c++;
        }
        return $sub_menu;
    }


    function index()
    {
        $_GET['status'] = 5;
        # 操作员ID号
        $op_id = $this->user->get_id();
        $sku = kernel::single('base_component_request')->get_get('sku');

        # 发货配置
        $deliCfgLib = kernel::single('wms_delivery_cfg');

        $title = '';

        $filter['type'] = 'normal';
        $filter['status'] = 3;
        $filter['shop_id'] = $this->getShopIds();
        // if (!$_POST['shop_id']) {
        //     $filter['shop_id'] = $this->shopIds;
        // } else {
        //     $filter['shop_id'] = $_POST['shop_id'];
        // }
        //分析status的filter条件
        $tmp_filter = $this->analyseStatus('');
        $filter = array_merge($filter, $tmp_filter);
        //获取操作员管辖仓库
        if ($_GET['btype'] == 2) {
            //导出的时候走这里取第三方仓
            $ownerBranch = array();
            $ownerBranch = kernel::single('ome_branch_type')->getOtherBranchLists();
        } else {
            //所有自建仓
            $ownerBranch = array();
            $ownerBranch = kernel::single('ome_branch_type')->getOwnBranchIds();
        }

        # 获取操作员管辖仓库
        $is_super = kernel::single('desktop_user')->is_super();
        if (!$is_super) {
            $oBranch = app::get('ome')->model('branch');
            $branch_ids = $oBranch->getBranchByUser(true);
            if ($branch_ids) {
                $filter['ext_branch_id'] = $_POST['branch_id'] ? $_POST['branch_id'] : $branch_ids;

                $filter['ext_branch_id'] = array_intersect($filter['ext_branch_id'], $ownerBranch);
            } else {
                $filter['ext_branch_id'] = 'false';
            }
        } else {
            $filter['ext_branch_id'] = $ownerBranch;
        }
        $attach = '&status=' . $_GET['status'] . '&logi_id=' . $_GET['logi_id'];
        if (isset($sku)) $attach .= '&sku=' . $sku;
        $use_buildin_import = false;
        $user = kernel::single('desktop_user');

        if ($user->has_permission('wms_process_receipts_print_export')) {
            $use_buildin_import = true;
        }
        $url = base_request::get_request_uri() . '&action=export';
        // echo"<pre>";var_dump($filter);die;
        $filter['is_sync_shop']='false';
        $params = array(
            'title' => '批量物流回传',
            'actions' => array(
                'stock' => array(
                    'label' => '批量回传',
                    'submit' => 'index.php?app=wms&ctl=admin_logiback_consign&act=toupdateAX',
                ),
                'updateStatus' => array(
                    'label' => '批量修改回传状态',
                    'confirm' =>'操作后会直接修改回传状态，请谨慎操作！！',
                    'submit' => 'index.php?app=wms&ctl=admin_logiback_consign&act=toupdateStatus',
                    'target' => 'refresh',
                ),
            ),
            'base_filter' => $filter,
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            // 'use_buildin_export' => $use_buildin_import,
            // 'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'max_actions' => 8,
            'use_view_tab' => true,
            'finder_aliasname' => 'delivery_print' . $op_id,
            //从载方法 以解决 发货中未录入快递单号不能过滤的bug
            'object_method' => array('count' => 'count_logi_no', 'getlist' => 'getlist_logi_no'),
        );

        $rolesData = app::get('desktop')->model('hasrole')->getList('role_id', array('user_id' => $op_id));
        foreach ($rolesData as $key => $value) {
            if ($value['role_id'] == 7) {
                $is_printship = '1';
            }
        }

        # 多打印模板--独立按钮
        if ($_GET['status'] != 6) {
            $otmplModel = app::get('ome')->model('print_otmpl');
            $filter = array('disabled' => 'false', 'aloneBtn' => 'true', 'open' => 'true', 'type' => array('delivery', 'stock'));
            $aloneBtnList = $otmplModel->getList('id,btnName,type', $filter);

            $typeAct = array('delivery' => 'toPrintMerge', 'stock' => 'toPrintStock');
            foreach ($aloneBtnList as $key => $value) {
                $params['actions']['aloneBtn' . $key] = array(
                    'label' => $value['btnName'],
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=' . $typeAct[$value['type']] . $attach . '&otmplId=' . $value['id'],
                    'target' => '_blank',
                );
            }
            //独立按钮
            $expressObj = app::get('logisticsmanager')->model('express_template');
            $alone_filter = array('aloneBtn' => 'true', 'status' => 'true', 'template_type' => array('delivery', 'stock'));
            $alonexpressList = $expressObj->getList('template_id,btnName,template_type', $alone_filter);

            $typeelectl = array('delivery' => 'toPrintMergeNew', 'stock' => 'toPrintStockNew');
            foreach ($alonexpressList as $k => $v) {
                $params['actions']['aloneBtn' . $k] = array(
                    'label' => $v['btnName'],
                    'submit' => 'index.php?app=wms&ctl=admin_receipts_print&act=' . $typeelectl[$v['template_type']] . $attach . '&otmplId=' . $v['template_id'],
                    'target' => '_blank',
                );
            }
        }
        $this->finder('wms_mdl_delivery', $params);
    }
    /*
     * 分析状态
     */

    function analyseStatus($status, $type = 'normal')
    {
        $sku = kernel::single('base_component_request')->get_get('sku');
        $deliCfgLib = kernel::single('wms_delivery_cfg');
        if ($type == 'normal') {
            switch ($status) {
                case '':
                    $title = '全部';
                    $filter = array();
                    $filter['status'] = array('3');
                    break;
            }
        } elseif ($type == 'refunded') {
            switch ($status) {
                case '':
                    $title = '未发货';
                    $filter['status'] = array('0');
                    break;
                case 1:
                    $title = '未发货';
                    $filter['status'] = array('0');
                    break;
                case 2:
                    $title = '已发货';
                    $filter['status'] = 3;
                    break;
            }
        }
        // 打印类型
        if ($sku) {
            if ($sku == 'single') {
                $filter['skuNum'] = 1;
            } elseif ($sku == 'multi') {
                $filter['skuNum|than'] = 1;
            }
        }

        //默认条件
        $filter['disabled'] = 'false';

        $schema = app::get('ome')->model('delivery')->schema;
        if (isset($_POST['status']) && $schema['columns']['status']['type'][$_POST['status']]) {
            $filter['status'] = $_POST['status'];
        }

        $filter['_title_'] = $title;

        return $filter;
    }

    public function toupdateAX()
    {

        ini_set('memory_limit','512M');
        set_time_limit(600);
        $now = time();
        //add by ldward 20181111 添加批量物流回传全选功能
        $dlyModel    = app::get('wms')->model('delivery');
        $opObj       = app::get('ome')->model('operation_log');
        $deliveryBillLib = kernel::single('wms_delivery_bill');
        if ($_POST['isSelectedAll']=='_ALL_') 
        {
            $_GET['status'] = 5;
            # 操作员ID号
            $sku = kernel::single('base_component_request')->get_get('sku');

            # 发货配置
            $deliCfgLib = kernel::single('wms_delivery_cfg');

            $title = '';

            $filter['type'] = 'normal';
            $filter['status'] = 3;
            $filter['shop_id'] = $this->getShopIds();
            //分析status的filter条件
            $tmp_filter = $this->analyseStatus('');
            $filter = array_merge($filter, $tmp_filter);
            //获取操作员管辖仓库
            if ($_GET['btype'] == 2) {
                //导出的时候走这里取第三方仓
                $ownerBranch = array();
                $ownerBranch = kernel::single('ome_branch_type')->getOtherBranchLists();
            } else {
                //所有自建仓
                $ownerBranch = array();
                $ownerBranch = kernel::single('ome_branch_type')->getOwnBranchIds();
            }

            # 获取操作员管辖仓库
            $is_super = kernel::single('desktop_user')->is_super();
            if (!$is_super) {
                $oBranch = app::get('ome')->model('branch');
                $branch_ids = $oBranch->getBranchByUser(true);
                if ($branch_ids) {
                    $filter['ext_branch_id'] = $_POST['branch_id'] ? $_POST['branch_id'] : $branch_ids;

                    $filter['ext_branch_id'] = array_intersect($filter['ext_branch_id'], $ownerBranch);
                } else {
                    $filter['ext_branch_id'] = 'false';
                }
            } else {
                $filter['ext_branch_id'] = $ownerBranch;
            }
            $filter['is_sync_shop']='false';
            if($_POST['logi_id'])
            {
                $filter['logi_id']=$_POST['logi_id'];
            }
            if($_POST['product_bn'])
            {
                $filter['product_bn']=$_POST['product_bn'];
            }
            if($_POST['notproduct_bn'])
            {
                $filter['notproduct_bn']=$_POST['notproduct_bn'];
            }
            //每次默认前1000条
            $dly_list = $dlyModel->getList('delivery_id,delivery_bn,outer_delivery_bn,logi_name,shop_id',$filter,0,1000);   
        }else
        {
            $delivery_ids= $_POST['delivery_id'];
            $dly_list = $dlyModel->getList('delivery_id,delivery_bn,outer_delivery_bn,logi_name,shop_id',array('delivery_id'=>$delivery_ids));
        }
        $this->begin("index.php?app=wms&ctl=admin_logiback_consign&act=index");
        $result = array();
        foreach($dly_list as $dly){
             //判断是否调用物流回传接口

            $logi_no = $deliveryBillLib->getPrimaryLogiNoById($dly['delivery_id']);
            $Oshop = app::get('ome')->model('shop');
            $shop = $Oshop->dump(array('shop_id' => $dly['shop_id']),'shop_bn,is_sendshop,isWD');
            list($usec, $sec) = explode(" ", microtime());
            if($shop['isWD'] == 'true')
            {
                //调用回传物流信息的接口
                $delivery_bn = $dly['delivery_bn'];
                $Oome_delivery = app::get('ome')->model('delivery');
                $Oome_delivery_order = app::get('ome')->model('delivery_order');
                $Oome_orders = app::get('ome')->model('orders');
                $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                $ome_delivery_order = $Oome_delivery_order->dump(array('delivery_id' => $ome_delivery['delivery_id']),'order_id');
                $ome_orders = $Oome_orders->dump(array('order_id' => $ome_delivery_order['order_id']),'order_bn');
                $order_bn = $ome_orders['order_bn'];
                $logi_no = $logi_no;
                $logi_name = $dly['logi_name'];
                $ret = kernel::single('ome_UpdateAXStatus')->UpdateAXStatus($shop['shop_bn'],$delivery_bn,$order_bn,$logi_no,$logi_name);
                $dlyModel->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                $ret=true;
            }elseif($shop['isWD'] == 'false'){
                $Oome_delivery = app::get('ome')->model('delivery');
                $ome_delivery = $Oome_delivery->dump(array('delivery_bn' => $dly['outer_delivery_bn']),'delivery_id');
                //update by ldward 201113平台接口回传物流信息，不能直接修改状态
                $Oome_delivery->call_delivery_api($ome_delivery['delivery_id'],false);
                

                $sql="SELECT log.log_id FROM  sdb_ome_delivery_order odo 
                                inner join sdb_ome_orders os on odo.order_id=os.order_id
                                inner join sdb_ome_shipment_log log on os.order_bn=log.orderBn  
                                where odo.delivery_id=".$ome_delivery['delivery_id']." and log.status='succ'";
                $rows = kernel::database()->select($sql);
                if (!empty($rows)) 
                {
                    $dlyModel->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                }else
                {
                    $logdata = $opObj->read_log(array('obj_id'=>$dly['delivery_id'],'obj_type'=>'delivery@wms'), 0, -1);
                    foreach($logdata as $k=>$v)
                    {
                        if($v['memo']=='物流回传成功')
                        {
                            $dlyModel->db->exec("update sdb_wms_delivery set is_sync_shop = true where  delivery_id ='" . $dly['delivery_id'] . "'");
                            break;
                        }
                    }
                }                
                $ret=true;
            }
            if(!isset($ret) || empty($ret)){
                $result[] = 'false';
                $opObj->write_log('delivery_check@wms', $dly['delivery_id'], '物流回传失败');
                error_log(date('Y-m-d H:i:s') . '批量物流回传/' . var_export($dly['delivery_bn'], true) . '失败'.PHP_EOL, 3, DATA_DIR . '/AlltoUpdateStatus_' . date('Y-m-d') . '.log');
                continue;
            }
            $opObj->write_log('delivery_check@wms', $dly['delivery_id'], '物流回传成功');
            error_log(date('Y-m-d H:i:s') . '批量物流回传/' . var_export($dly['delivery_bn'], true) . '成功'.PHP_EOL, 3, DATA_DIR . '/AlltoUpdateStatus_' . date('Y-m-d') . '.log');
        }
        if(in_array('false',$result)){
            $this->end(true, '批量回传失败');
        }
        $this->end(true, '批量回传完成');

    }


    public function toupdateStatus(){
        $this->begin("");
        $delivery_ids= $_POST['delivery_id'];
        $dlyModel    = app::get('wms')->model('delivery');
        foreach($delivery_ids as $id){
            $params=array(
                'delivery_id'=>$id,
                'is_sync_shop'=>'true',
            );
            $dlyModel->save($params);
        }

        $this->end(true, '批量修改回传状态完成');
    }

}
?>
